package com.whosly.strategy.container;

import com.whosly.strategy.IStrategy;

/**
 * 并发安全的容器加载服务
 *
 * @author fengyang <deep_blue_yang@126.com>
 * @date 2020/10/11  3:51 下午
 * @title: StrategyContainerAtomicImpl
 * @projectName rapid-strategy
 * @description:
 */
public abstract class StrategyContainerAtomicImpl<C, S extends IStrategy<C>>
        extends StrategyContainerImpl<C, S> {

    /**
     * 是否已经完成第一次存量实例化
     */
    private volatile boolean inited = Boolean.FALSE;

    @Override
    public S getStrategy(final C condition) {
        if (needInit(condition)) {
            synchronized (this){
                if(needInit(condition)){
                    initStrategyBean();

                    this.inited = true;
                }
            }
        }

        return getStrategyMap().get(condition);
    }

    private boolean needInit(C condition) {
        // 不为空， 且未进行过初始化，均满足才会进行初始化。否则均进行初始化
        return !getStrategyMap().containsKey(condition) && !this.inited;
    }

}
